package com.iceland.server.server.proxy;

import com.iceland.server.server.Server;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class ProxyServerManager {
    private static ProxyServerManager proxyServerManager=new ProxyServerManager();
    private ProxyServerManager(){}
    public static ProxyServerManager getSingleInstance(){
        return proxyServerManager;
    }

    private Map<Integer, Server> proxyServerMap=new ConcurrentHashMap<>();

    /**
     * 启动一个服务
     * @param port 端口为0时，启动任一空闲端口
     * @return 返回启动的端口
     */
    public int addServer(int port) throws Exception {
        if(proxyServerMap.containsKey(port)){
            throw new Exception(port+"端口已经被绑定");
        }
        Server server=new ProxyServer();
        if(port!=0){
            //先把该端口占用了
            synchronized (this) {
                if(proxyServerMap.containsKey(port)) {
                    throw new Exception("端口"+port+"已经被绑定");
                }
                proxyServerMap.put(port, server);
            }
        }

        try {
            int realPort = server.startServer(port);
            if(port==0){
                synchronized (this) {
                    if(proxyServerMap.containsKey(realPort)) {
                        throw new Exception("端口"+realPort+"已经被绑定");
                    }
                    proxyServerMap.put(realPort, server);
                    return realPort;
                }
            }
        } catch (Exception e) {
            //服务启动失败
            if(port!=0){
                proxyServerMap.remove(port);
            }
            throw e;
        }
        return port;

    }

    public ProxyServer getServer(int port){
        return (ProxyServer)proxyServerMap.get(port);
    }

    public void closeServer(int port){
        Server server = proxyServerMap.remove(port);
        log.info("正在关闭代理服务器，端口：{}",port);
        server.close();
        log.info("已经关闭代理服务器，端口：{}",port);
    }
}
